<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Video;
use Illuminate\Support\Str;
use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;

use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;
use Illuminate\Support\Facades\Storage;

class splitVideo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:split-video';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $video = Video::find(416);
        $videoUrl = $video->video_url;

        

        //$videoUrl = str_replace('&', '\&', $videoUrl);
        $postName = Str::random(40). '.mp4';
        $outVideoPutFile =storage_path('app/public')."/".$postName; // 输出视频文件

        $postAudioName = Str::random(40). '.mp3';
        $outAudioPutFile =storage_path('app/public')."/".$postAudioName; // 输出音频文件

        $postZmName = Str::random(40). '.srt';
        $outZmPutFile =storage_path('app/public')."/".$postZmName; // 输出字幕文件

        exec("ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl." -ss 0 -t 10 -vn -ar 44100 -ac 2 -ab 192k -f  mp3 $outAudioPutFile");



        dd($outAudioPutFile);
        /*exec("ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl." -c copy -an -sn $outVideoPutFile");
        exec("ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl." -c:s copy  $outZmPutFile");
        dd(123);*/
       // exec("ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl." -vn -ar 44100 -ac 2 -ab 192k -f mp3 $outAudioPutFile");

      


        $client = self::createClient();
        $params = self::createApiInfo("74985ead597148abb603213ed57eb713");
        // runtime options
        $runtime = new RuntimeOptions([]);
        $request = new OpenApiRequest([]);
        // 复制代码运行请自行打印 API 的返回值

        // 返回值实际为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        $res = $client->callApi($params, $request, $runtime);

        $translateJsonUrl = $res['body']['Data']['Result']['Translation'];
        $translateJson = file_get_contents($translateJsonUrl);
        $translateArr = json_decode($translateJson,true);

        $content = "";

        $i=0;
        foreach($translateArr['Translation']['Paragraphs'] as $k=>$v){

            foreach($v['Sentences'] as $kk=>$vv){
                $content.=($i+1)."\n";
                $content.=$this->seconds2SRT($vv['Start']/1000) . ' --> ' . $this->seconds2SRT($vv['End']/1000) . "\n";
                $content .= $vv['Text'] . "\n\n"; // 双换行符分隔字幕段落
                $i++;
            }

        }


        Storage::disk('public')->put($postZmName, $content);
        
        dd($content);




         $client = self::createClient();
        $params = self::createApiInfo();

       
       
        // query params
        $queries = [];
        $queries["type"] = "offline";
        // body params
        $body = [
            "Input" => [
                "FileUrl" => $videoUrl,
                "SourceLanguage" => "cn"
            ],
            "Parameters" => [

                "Translation" => [
                    "TargetLanguages" => [
                        "en"
                    ],
                     "OutputLevel" => 1,
                ],
                "TranslationEnabled" => true,
                "MeetingAssistanceEnabled" => false,
                "TextPolishEnabled"=>true,
                "SummarizationEnabled" => true,
                "Summarization" => [
                    "Types" => [
                        "Paragraph"
                    ]
                ],
                "CustomPrompt"=>[
                    "Contents"=>[
                        [
                            "Name"=>"split-summary-demo",
                            "Prompt"=> "请以字幕翻译专家的口吻重新翻译:\n {Transcription}",
                            "Model"=> "tingwu-turbo",
                            "TransType"=>"chat"
                        ],
                      
                    ]
                ]

            ],
            "AppKey" => "FPzj7g7IeJj7YKn6"
        ];
        // runtime options
        $runtime = new RuntimeOptions([]);
        $request = new OpenApiRequest([
            "query" => OpenApiUtilClient::query($queries),
            "body" => $body
        ]);
        // 复制代码运行请自行打印 API 的返回值
        
        // 返回值实际为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        $res = $client->callApi($params, $request, $runtime);

        
        if($res['body']['Message'] == 'success'){

            var_dump($res['body']['Data']['TaskId']);

            //$video->update(['task_id'=>$res['body']['Data']['TaskId']]);

            //dispatch(new VideoTranslateJob($video))->onQueue('video');

        }


       /* exec("ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl." -c copy -an $outVideoPutFile");
        exec("ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl." -vn -ar 44100 -ac 2 -ab 192k -f mp3 $outAudioPutFile");*/

        //exec("ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i ".$videoUrl." -vn -an  $outZmPutFile");

        
    }

    public static function createClient(){
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => env("ALIYUN_TINGWU_ACCESS_KEY_ID"),
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => env("ALIYUN_TINGWU_ACCESS_KEY_SECRET")
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/tingwu
        $config->endpoint = "tingwu.cn-beijing.aliyuncs.com";
        return new OpenApiClient($config);
    }

    /**
     * API 相关
     * @return Params OpenApi.Params
     */
    /*public static function createApiInfo(){
        $params = new Params([
            // 接口名称
            "action" => "CreateTask",
            // 接口版本
            "version" => "2023-09-30",
            // 接口协议
            "protocol" => "HTTPS",
            // 接口 HTTP 方法
            "method" => "PUT",
            "authType" => "AK",
            "style" => "ROA",
            // 接口 PATH
            "pathname" => "/openapi/tingwu/v2/tasks",
            // 接口请求体内容格式
            "reqBodyType" => "json",
            // 接口响应体内容格式
            "bodyType" => "json"
        ]);
        return $params;
    }*/

    public static function createApiInfo($taskId){

         $params = new Params([
            // 接口名称
            "action" => "GetTaskInfo",
            // 接口版本
            "version" => "2023-09-30",
            // 接口协议
            "protocol" => "HTTPS",
            // 接口 HTTP 方法
            "method" => "GET",
            "authType" => "AK",
            "style" => "ROA",
            // 接口 PATH
            "pathname" => "/openapi/tingwu/v2/tasks/". $taskId,
            // 接口请求体内容格式
            "reqBodyType" => "json",
            // 接口响应体内容格式
            "bodyType" => "json"
        ]);
        return $params;
    }

    private function seconds2SRT($seconds)
    {
        $hours = 0;
        $whole = floor($seconds);
        $fraction = $seconds - $whole;
        $milliseconds = number_format($fraction, 3, '.', ',');

        $milliseconds_array = explode('.', strval($milliseconds));

        if(!empty($milliseconds_array)){

              $milliseconds = $milliseconds_array[1];
        }
      

        if ($seconds > 3600) {

            $hours = floor($seconds / 3600);


        }


        $seconds = (int)$seconds % 3600;

        
        return str_pad($hours, 2, '0', STR_PAD_LEFT)
            . gmdate(':i:s', $seconds)
            . ($milliseconds ? ",$milliseconds" : '');
    }
}
